package com.scu.phototabuser.ui.home;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;

import com.google.gson.Gson;
import com.scu.phototabuser.Consts;
import com.scu.phototabuser.MainDecisionMaker;
import com.scu.phototabuser.R;
import com.scu.phototabuser.data.Taskable;
import com.scu.phototabuser.data.source.remote.RefreshTokenTaskable;
import com.scu.phototabuser.data.source.remote.Response;
import com.scu.phototabuser.http.OkHttp3Methods;
import com.scu.phototabuser.ui.navitems.AboutUs;
import com.scu.phototabuser.ui.navitems.MineDetailActivity;
import com.scu.phototabuser.ui.navitems.Settings;
import com.scu.phototabuser.util.FragmentUtil;
import com.scu.phototabuser.util.PreferenceUtil;
import com.scu.phototabuser.util.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by tianfei on 2017/4/9.
 */

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,
        View.OnClickListener{


    @BindView(R.id.toolbar) Toolbar toolbar;

    @BindView(R.id.nav_view) NavigationView navigationView;

    @BindView(R.id.drawer_layout) DrawerLayout drawer;
    //替换主界面的Fragment
    @BindView(R.id.home_container) FrameLayout container;

    @BindView(R.id.img_btn_home) ImageButton bar_btn_home;
    @BindView(R.id.img_btn_history) ImageButton bar_btn_history;
    @BindView(R.id.img_btn_mine) ImageButton bar_btn_mine;

    private MissionFragment missionFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.navigation_drawer_view);
        ButterKnife.bind(this);

        toolbar.setTitle(getResources().getString(R.string.app_name));
        toolbar.setTitleTextColor(ContextCompat.getColor(HomeActivity.this, R.color.colorAccent));
        setSupportActionBar(toolbar);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        bar_btn_history.setOnClickListener(this);
        bar_btn_home.setOnClickListener(this);
        bar_btn_mine.setOnClickListener(this);


        missionFragment = MissionFragment.newInstance();
        MissionPresenter mPresenter = new MissionPresenter(missionFragment);
        bar_btn_home.callOnClick();

        //检查用户登录状态

        if (!getIntent().getBooleanExtra("fromlogin",false)) {
            checkUserLoginState();
        }
    }

    private void checkUserLoginState() {
        loginWithToken();
    }

    private void loginWithToken() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Integer> e) throws Exception {

                String json= OkHttp3Methods.PostRequestWithToken(Consts.LoginWithToken,null);

                Response res=new Gson().fromJson(json,Response.class);

                if (res.getCode() != 200 && res.getCode() !=403){
                    e.onError(new RuntimeException(res.getMessage()));
                }else{
                    e.onNext(res.getCode());
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {}

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull Integer i) {

                        if (i==403){
                            new RefreshTokenTaskable(){

                                @Override
                                protected void onSuccess(String data) {
                                    PreferenceUtil.saveToken(data);
                                    ToastUtil.makeToast(HomeActivity.this,getString(R.string.login_success));
                                }

                                @Override
                                protected void onFailed(Integer code, String msg) {

                                    Log.e("Refresh Token---", "onError: "+msg);
                                    ToastUtil.makeToast(HomeActivity.this,getString(R.string.account_exception));
                                    PreferenceUtil.clearLoginState();
                                    Intent i2Start=new Intent(HomeActivity.this, MainDecisionMaker.class);
                                    i2Start.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(i2Start);
                                }
                            }.start(Taskable.TASK_TYPE.TOKEN);
                        }else {
                            ToastUtil.makeToast(HomeActivity.this,getString(R.string.login_success));
                        }

                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        ToastUtil.makeToast(HomeActivity.this,e.getMessage());
                    }

                    @Override
                    public void onComplete() {}
                });
    }


    //如果侧滑栏是打开的，按下返回键后关闭侧滑栏而不是关闭Activity
    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {


        switch (item.getItemId()){
            case R.id.nav_account:
                Intent i2Mine =new Intent(HomeActivity.this, MineDetailActivity.class);
                startActivity(i2Mine);
                break;
            // FIXME: 2017/5/9
            case R.id.nav_settings:
                Intent i2Setting=new Intent(HomeActivity.this, Settings.class);
                startActivity(i2Setting);
                break;
            case R.id.nav_coming_soon:
                // FIXME: 2017/5/10
                ToastUtil.makeToast(HomeActivity.this,"更多功能，敬请期待！");
                break;
            case R.id.about_us:
                AboutUs abs=AboutUs.newInstance();
                abs.show(getFragmentManager(),null);
                break;
            default:
                break;
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.img_btn_home:
                if (fragmentFlag!=0){
                    replaceContainer(missionFragment);
                    clearAllButtonClickState();
                    bar_btn_home.setBackground(getDrawable(R.drawable.ic_home_pressed));
                }
                break;
            case R.id.img_btn_history:
                if (fragmentFlag!=1){

                    // FIXME: 2017/5/10  删除 fragmentFlag = x; 在replace中已经做过修改flag
                    fragmentFlag = 1;
                    //replaceContainer(null);\
                    clearAllButtonClickState();
                    bar_btn_history.setBackground(getDrawable(R.drawable.ic_history_pressed));
                }
                break;
            case R.id.img_btn_mine:
                if (fragmentFlag!=2){
                    // FIXME: 2017/5/10
                    fragmentFlag = 2;
                    //replaceContainer(null);
                    clearAllButtonClickState();
                    bar_btn_mine.setBackground(getDrawable(R.drawable.ic_mine_pressed));
                }
                break;
            default:break;
        }
    }

    public void clearAllButtonClickState(){
        bar_btn_home.setBackground(getDrawable(R.drawable.ic_home_custom));
        bar_btn_history.setBackground(getDrawable(R.drawable.ic_history_custom));
        bar_btn_mine.setBackground(getDrawable(R.drawable.ic_mine_custom));
    }

    // 0 ---> MissionFragment
    private int fragmentFlag = -1;
    public void replaceContainer(Fragment f){
        if (f instanceof MissionFragment && fragmentFlag!= 0){
            fragmentFlag = 0 ;
            FragmentUtil.addFragmentToActivity(getFragmentManager(),R.id.home_container,
                    f,null,false);
        }else {

            // FIXME: 2017/5/10

            return;
        }
    }
}
